import a from 'axios'
import ls from 'store2'

const axios = a.create({
	headers: {
		"Accept":"application/json"
	},
	baseURL: '/schoolApi',
	timeout: 3000000
})

const getHeaderLogin = () => {
	
	let headers = {
	}

	return headers
}
const getHeader = () => {
	
	let headers = {
		"Accept":"application/json",
		'Authorization': 'bearer ' + ls.get('tokensyxk') 
	}

	return headers
}


// 返回状态判断
axios.interceptors.response.use((res) => {
	console.log('resres',res)
	if (res.status === 200) {
		res.data.success = res.data.code === 0
		return res.data
	} else {
		return Promise.reject(res)
	}
}, (error) => {
	if (error && error.response && error.response.status === 401) {
		// window.$nuxt.$store.commit('setLoginDisplay', true)
		Message({
			title: '提示',
			message: '登录已失效，请重新登录',
			type: 'error',
			center: true,
			showClose: false,
			duration: 2000
		})
		window.$nuxt.$store.commit('clearToken')
		window.$nuxt.$router.replace('/login')
	}
	return Promise.reject(error)
})

let loginLoading = false;
let loginPromise;
let methods = {
	put_http(url, params) {
		return axios({
			method: 'PUT',
			url,
			data: params,
			headers: getHeader()
		})
	},
	gets(url, params) {
		return axios({
			method: 'GET',
			url,
			data: params,
			headers: getHeader()
		})
	},
	delete_http(url, params) {
		return axios({
			method: 'DELETE',
			url,
			data: params,
			headers: getHeader()
		})
	},
	post_http(url, params) {
		return axios({
			method: 'POST',
			url,
			data: params,
			headers: url == '/university/login' ? getHeaderLogin() : getHeader()
		})
	},
	postForm_http(url, params) {
		let headers = getHeader()
		headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
		return axios({
			method: 'POST',
			url,
			data: qs.stringify(params),
			headers
		})
	},
	get_http(url, params) {
		return axios({
			method: 'GET',
			url,
			params,
			headers: getHeader()
		})
	},
	put(url, params, requireLogin) {
		if (requireLogin && loginLoading) {
			return loginPromise.then(() => {
				return this.put_http(url, params)
			})
		} else {
			return this.put_http(url, params)
		}
	},
	del(url, params, requireLogin) {
		if (requireLogin && loginLoading) {
			return loginPromise.then(() => {
				return this.delete_http(url, params)
			})
		} else {
			return this.delete_http(url, params)
		}
	},
	get(url, params, requireLogin) {
		if (requireLogin && loginLoading) {
			return loginPromise.then(() => {
				return this.get_http(url, params)
			})
		} else {
			return this.get_http(url, params)
		}
	},
	post(url, params, requireLogin) {
		if (requireLogin && loginLoading) {
			return loginPromise.then(() => {
				return this.post_http(url, params)
			})
		} else {
			return this.post_http(url, params)
		}
	}
}
export default methods
